<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="任务名称">
            <el-input v-model="queryParams.periodic_task_name" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="执行函数名称">
            <el-input v-model="queryParams.task_name" placeholder="请输入执行函数名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="任务状态"  style="width: 200px;">
            <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
            <el-button :icon="RefreshRight" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="mb-2 flex justify-between">
        <div>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
          <el-button type="danger" @click="handleClearOldResults">清理旧结果</el-button>
        </div>
        <div>
          <el-input v-model="searchValue" placeholder="请输入关键字搜索" style="width: 200px;" clearable @keyup.enter="handleSearch" />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="taskResultList"
        border
        style="width: 100%; margin-bottom: 20px; table-layout: fixed;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column prop="id" label="结果ID" width="80" align="center" />
        <el-table-column prop="periodic_task_name" label="任务名称" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="task_name" label="任务函数名称" min-width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status_display || scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="参数" width="120" align="center">
          <template #default="scope">
            <el-tooltip effect="dark" placement="top" :content="JSON.stringify(scope.row.parsed_kwargs || {})">
              <el-button size="small" type="info" plain>查看</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="date_created" label="创建时间" width="160" align="center" show-overflow-tooltip />
        <el-table-column prop="date_done" label="完成时间" width="160" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialog" title="任务结果详情" width="700px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务ID">{{ detailForm.task_id }}</el-descriptions-item>
          <el-descriptions-item label="任务名称">{{ detailForm.task_name }}</el-descriptions-item>
          <el-descriptions-item label="执行状态">
            <el-tag :type="getStatusTagType(detailForm.status)">{{ detailForm.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailForm.date_created }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ detailForm.date_done }}</el-descriptions-item>
          <el-descriptions-item label="执行耗时">{{ getExecutionTime(detailForm) }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">任务参数</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <h4>位置参数</h4>
            <el-input
              v-model="formattedTaskArgs"
              type="textarea"
              :rows="5"
              readonly
            />
          </el-col>
          <el-col :span="12">
            <h4>关键字参数</h4>
            <el-input
              v-model="formattedTaskKwargs"
              type="textarea"
              :rows="5"
              readonly
            />
          </el-col>
        </el-row>

        <el-divider content-position="left">执行结果</el-divider>
        <el-input
          v-model="formattedTaskResult"
          type="textarea"
          :rows="5"
          readonly
        />

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialog = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 清理旧结果对话框 -->
      <el-dialog v-model="clearDialog" title="清理旧任务结果" width="500px">
        <el-form :model="clearForm" label-width="120px">
          <el-form-item label="保留天数">
            <el-input-number v-model="clearForm.days" :min="1" :max="365" />
            <div class="form-help">设置要保留的天数，将删除此天数之前的所有任务结果</div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="clearDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmClearOldResults">确认清理</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight } from '@element-plus/icons-vue'
import requestUtil from '@/util/request'

// 任务状态选项
const statusOptions = [
  { value: 'SUCCESS', label: '成功' },
  { value: 'FAILURE', label: '失败' },
  { value: 'PENDING', label: '等待中' },
  { value: 'STARTED', label: '执行中' },
  { value: 'RETRY', label: '重试' },
  { value: 'REVOKED', label: '已取消' }
]

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    'SUCCESS': 'success',
    'FAILURE': 'danger',
    'PENDING': 'info',
    'STARTED': 'warning',
    'RETRY': 'warning',
    'REVOKED': 'info'
  }
  return statusMap[status] || 'info'
}

// 计算执行时间
const getExecutionTime = (row) => {
  if (!row.date_created || !row.date_done) return '未完成'
  
  try {
    const startTime = new Date(row.date_created)
    const endTime = new Date(row.date_done)
    const diffMs = endTime - startTime
    
    // 如果小于1秒
    if (diffMs < 1000) {
      return `${diffMs}毫秒`
    }
    
    // 如果小于1分钟
    if (diffMs < 60 * 1000) {
      return `${Math.floor(diffMs / 1000)}秒`
    }
    
    // 如果小于1小时
    if (diffMs < 60 * 60 * 1000) {
      const minutes = Math.floor(diffMs / (60 * 1000))
      const seconds = Math.floor((diffMs % (60 * 1000)) / 1000)
      return `${minutes}分${seconds}秒`
    }
    
    // 如果大于等于1小时
    const hours = Math.floor(diffMs / (60 * 60 * 1000))
    const minutes = Math.floor((diffMs % (60 * 60 * 1000)) / (60 * 1000))
    const seconds = Math.floor((diffMs % (60 * 1000)) / 1000)
    return `${hours}时${minutes}分${seconds}秒`
  } catch (e) {
    console.error('计算执行时间出错', e)
    return '计算错误'
  }
}

// 数据加载状态
const loading = ref(false)
// 任务结果列表数据
const taskResultList = ref([])
// 总记录数
const total = ref(0)
// 选中的记录ID
const selectedIds = ref([])
// 搜索关键字
const searchValue = ref('')
// 详情对话框显示状态
const detailDialog = ref(false)
// 清理对话框显示状态
const clearDialog = ref(false)
// 详情表单数据
const detailForm = ref({})
// 清理表单数据
const clearForm = ref({
  days: 30
})
// 日期范围
const dateRange = ref([])

// 查询参数
const queryParams = ref({
  page: 1,
  page_size: 10,
  task_name: '',
  status: '',
  start_date: '',
  end_date: '',
  ordering: '-date_done' // 默认按完成时间降序
})

// 格式化的任务位置参数
const formattedTaskArgs = computed(() => {
  if (!detailForm.value.parsed_args) return ''
  try {
    return JSON.stringify(detailForm.value.parsed_args, null, 2)
  } catch (e) {
    if (detailForm.value.task_args) {
      try {
        const argsObj = JSON.parse(detailForm.value.task_args)
        return JSON.stringify(argsObj, null, 2)
      } catch (e) {
        return detailForm.value.task_args
      }
    }
    return ''
  }
})

// 格式化的任务关键字参数
const formattedTaskKwargs = computed(() => {
  if (!detailForm.value.parsed_kwargs) return ''
  try {
    return JSON.stringify(detailForm.value.parsed_kwargs, null, 2)
  } catch (e) {
    if (detailForm.value.task_kwargs) {
      try {
        const kwargsObj = JSON.parse(detailForm.value.task_kwargs)
        return JSON.stringify(kwargsObj, null, 2)
      } catch (e) {
        return detailForm.value.task_kwargs
      }
    }
    return ''
  }
})

// 格式化的任务结果
const formattedTaskResult = computed(() => {
  if (!detailForm.value.result) return ''
  try {
    const resultObj = JSON.parse(detailForm.value.result)
    return JSON.stringify(resultObj, null, 2)
  } catch (e) {
    return detailForm.value.result
  }
})

// 获取任务结果列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = { ...queryParams.value }
    if (searchValue.value) {
      params.search = searchValue.value
    }
    const response = await requestUtil.get('/tasks/task_result/', params)
    taskResultList.value = response.results || []
    total.value = response.count || 0
  } catch (error) {
    console.error('获取任务结果列表失败', error)
    ElMessage.error('获取任务结果列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮点击事件
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.value.task_name = ''
  queryParams.value.status = ''
  queryParams.value.start_date = ''
  queryParams.value.end_date = ''
  dateRange.value = []
  searchValue.value = ''
  handleQuery()
}

// 搜索按钮点击事件
const handleSearch = () => {
  queryParams.value.page = 1
  getList()
}

// 日期范围变化事件
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.value.start_date = val[0]
    queryParams.value.end_date = val[1]
  } else {
    queryParams.value.start_date = ''
    queryParams.value.end_date = ''
  }
}

// 表格选择变化事件
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化事件
const handleSizeChange = (val) => {
  queryParams.value.page_size = val
  getList()
}

// 当前页变化事件
const handleCurrentChange = (val) => {
  queryParams.value.page = val
  getList()
}

// 查看详情
const handleDetail = (row) => {
  detailForm.value = { ...row }
  detailDialog.value = true
}

// 删除单条记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除任务结果 ${row.task_name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.delete(`/tasks/task_result/${row.id}/`)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条任务结果吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.post('/tasks/task_result/batch_delete/', { ids: selectedIds.value })
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 打开清理旧结果对话框
const handleClearOldResults = () => {
  clearDialog.value = true
}

// 确认清理旧结果
const confirmClearOldResults = async () => {
  try {
    await requestUtil.post('/tasks/task_result/clear_old_results/', { days: clearForm.value.days })
    ElMessage.success('清理成功')
    clearDialog.value = false
    getList()
  } catch (error) {
    console.error('清理失败', error)
    ElMessage.error('清理失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.form-help {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
